﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PowersourceUIToolkit;
using UCL.Powersource.Helpers;
using UCL.Powersource.ViewModels;

namespace UCL.Powersource.Views
{
    /// <summary>
    /// Interaction logic for PowersourceMainView.xaml
    /// </summary>
    [Export(typeof(PowersourceMainView))]
    public partial class PowersourceMainView : UserControl
    {
        private ILog Log;

        public PowersourceMainView()
        {
            Log = LogManager.GetLog(typeof(PowersourceMainView));
            this.Initialized += PowersourceMainView_Initialized;
            InitializeComponent();
            this.Loaded += PowersourceMainView_Loaded;
            this.Unloaded += PowersourceMainView_Unloaded;
        }

        void PowersourceMainView_Initialized(object sender, EventArgs e)
        {
            Log.TraceMethod();
        }

        void PowersourceMainView_Unloaded(object sender, RoutedEventArgs e)
        {
            Log.TraceMethod();
            if (VM != null)
            {
                VM.Deactivate();
                VM.ViewConfig.PropertyChanged -= ViewConfig_PropertyChanged;
            }
        }

        PowersourceMainViewModel VM { get { return (PowersourceMainViewModel)DataContext; } }

        void PowersourceMainView_Loaded(object sender, RoutedEventArgs e)
        {
            Log.TraceMethod();
            if (VM != null)
            {
                Log.Trace("Activating VM {0}", VM.GetHashCode());
                VM.Activate();
                VM.ViewConfig.PropertyChanged += ViewConfig_PropertyChanged;
                VisualStateManager.GoToState(this, VM.ViewConfig.ViewModelState.ToString(), true);
            }

        }

        void ViewConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            //VisualStateManager vsm=new VisualStateManager();

            if (PropertyExtensions.IsPropertyChanged(e, () => VM.ViewConfig.ViewModelState))
            {
                VisualStateManager.GoToState(this, VM.ViewConfig.ViewModelState.ToString(), true);
            }
        }
    }
}